import { useState, useEffect } from 'react';
import { styled } from '@mui/material/styles';
import fetchData from '../../utils/ApiFetch';
import {Box, Breadcrumbs, Button, ButtonGroup, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Divider, IconButton, Link, ListItemIcon, ListItemText, Menu, MenuItem, Snackbar, TextField } from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import CreateNewFolderIcon from '@mui/icons-material/CreateNewFolder';
import { useSelector, useDispatch } from 'react-redux';
import './file-panel.css'

import { changeFileParentId, backward, backwardUnit } from '../../app/features/koalaFilePanelSlice';
import { useNavigate } from 'react-router-dom';
import Bread from '../Bread/Bread';
import FilesContainer from '../FilesContainer/FilesContainer';
import FileToolsBar from '../FileToolsBar/FileToolsBar';
import CommonToolBar from '../CommonToolbar/CommonToolBar';
import doFileUpload from '../../utils/FileUpload';
import ProgressPanel from '../ProgressPanel/ProgressPanel';
import UploadPanel from '../UploadPanel/UploadPanel';
import { setProgressOpen } from '../../app/features/progressSlice';

const apiUrl = process.env.REACT_APP_API_URL;
const debugMode = process.env.REACT_APP_DEBUG_MODE === 'true';

const VisuallyHiddenInput = styled('input')({
    clip: 'rect(0 0 0 0)',
    clipPath: 'inset(50%)',
    height: 1,
    overflow: 'hidden',
    position: 'absolute',
    bottom: 0,
    left: 0,
    whiteSpace: 'nowrap',
    width: 1,
  });

function FilePanel() {
    const parentId = useSelector(state => state.koalaFilePanelReducer.fileParentId);
    const disableBack = useSelector(state => state.koalaFilePanelReducer.fileHistory.length === 0);
    const uploadList = useSelector(state => state.progressReducer.uploadList);
    const [error, setError] = useState(false);
    const [refresh, setRefresh] = useState(false);
    const dispatch = useDispatch();
    const [files, setFiles] = useState([]);
    const [open, setOpen] = useState(false);
    const [newFolderName, setNewFolderName] = useState('');
    const [contextMenu, setContextMenu] = useState(null);
    const [selectedFiles, setSelectedFiles] = useState([]);
    const [filePath, setFilePath] = useState([]);
    const [hasMsg, setHasMsg] = useState(false);
    const [message, setMessage] = useState(false);
    const navigate = useNavigate()
    useEffect(() => {
        const fetchFiles = async () => {
            try {
                const resp = await fetchData(`${apiUrl}/user/getFiles?parentId=${parentId}`);
                console.log(resp);
                if (resp.code === 401) {
                    navigate('/signin')
                    localStorage.removeItem('token')
                } else {
                    setError(false)
                    setFiles(resp.data.files.map((e) => { e.selected = false; return e}))
                }
            } catch (error) {
                console.log(error);
            }
        }
        fetchFiles();
        
    }, [parentId, refresh]);
    let lastClick = null;
    function changeParentId(item) {
        if (item.type === 1 && lastClick === item.id) {
            setFilePath(filePath.concat({id: item.id, name: item.fileName}))
            dispatch(changeFileParentId(item.id));
        }
        lastClick = item.id;
        setTimeout(() => lastClick = null, 1000);
    }

    useEffect(()=> {
        let newSelectedFile = []
        files.forEach((e) => {
            if (e.selected) {
                newSelectedFile.push(e)
            }
        })
        setSelectedFiles(newSelectedFile)
    }, [files])

    function back() {
        setFilePath(filePath.slice(0, -1))
        dispatch(backward())
    }
    function handleFileNameChange(file, newFileName) {
        const renameFiles = async () => {
            try {
                const resp = await fetchData(`${apiUrl}/file/rename`, 'POST', {fileId: file.id, newName: newFileName});
                console.log(resp);
                setRefresh(!refresh)
            } catch (error) {
                console.log(error);
            }
        }
        renameFiles();
    }

    function handleContextMenuOpen(e) {
        e.preventDefault()
        setContextMenu(
            contextMenu === null
              ? {
                  mouseX: e.clientX + 2,
                  mouseY: e.clientY - 6,
                }
              :
                null,
          );
    }

    function handleContextClose(e) {
        setContextMenu(null)
    }

    function handleFileSelected(file, checked) {
        console.log(file, checked)
        let newFiles = []
        files.forEach((e)=> {
            if (e.id === file.id) {
                e.selected = checked;
            }
            newFiles.push(e)
        })
        setFiles(newFiles)
    }

    function handleFileUpload(e) {
        dispatch(setProgressOpen(true));
        const uploadFile = async () => {
            try {
                doFileUpload(e.target.files[0], parentId, dispatch, ()=>{
                    setMessage('文件上传成功');
                    setHasMsg(true);
                    setRefresh(!refresh);
                    e.target.value = '';
                });
            } catch (error) {
                console.log(error);
            }
        }
        uploadFile();
    }

    function handleNewFolderBtnClick(e) {
        setOpen(true)
        setNewFolderName('')
    }

    function handleClose(e) {
        setOpen(false)
        setNewFolderName('')
    }

    function handleNewFolderCreate(e) {
        if (newFolderName === '') {
            return
        }
        const newFolderCreate = async () => {
            try {
                const resp = await fetchData(`${apiUrl}/user/mkDir`, 'POST', {parentId: parentId, dirName: newFolderName});
                console.log(resp);
                setRefresh(!refresh)
            } catch (error) {
                console.log(error);
            }
        }
        newFolderCreate();
        setOpen(false)
    }



    function handleBreadClick(fileId) {
        let newFilePath = filePath.slice()
        while (newFilePath.length > 0 && newFilePath[newFilePath.length-1].id !== fileId) {
            newFilePath.pop()
        }
        setFilePath(newFilePath)
        dispatch(backwardUnit(fileId))
    }

    function handleSnackClose(e) {
        setHasMsg(false);
    }


    return (
        <Box sx={{flexGrow:'1'}}>
            <Box className='tool-bar-div'>
                <Box sx={{display:'flex'}}>
                    <IconButton aria-label="delete" onClick={back} disabled={disableBack}>
                        <ArrowBackIcon sx={{fontSize:'2rem'}} />
                    </IconButton>
                    <Box sx={{display:{xs: 'none', md: 'flex'}, alignItems:'center'}}>
                        <Breadcrumbs>
                            <Link key={0} sx={{fontWeight:'900'}} onClick={(e)=> {handleBreadClick(0)}} >我的文件</Link>
                            { filePath.map((path) => <Bread key={path.id} fileId={path.id} onBreadClick={handleBreadClick}  >{path.name}</Bread>) }
                        </Breadcrumbs>
                    </Box>
                </Box>
                
                <ButtonGroup sx={{marginTop:'6px', marginBottom:'6px'}} >
                    <Button component="label" variant="contained" startIcon={<CloudUploadIcon />}>
                        文件上传
                        <VisuallyHiddenInput type="file" onChange={handleFileUpload} />
                    </Button>
                    <Button variant="outlined" startIcon={ <CreateNewFolderIcon/> } onClick={handleNewFolderBtnClick} >
                        新建文件夹
                    </Button>
                </ButtonGroup>
            </Box>
            <Divider sx={{marginBottom:'12px'}}/>
            <CommonToolBar selectedFiles={selectedFiles} onDone={() => setRefresh(!refresh)}/>
            <FilesContainer files={files} error={error} handleContextMenuOpen={handleContextMenuOpen} onClick={changeParentId} handleFileNameChange={handleFileNameChange} handleFileSelected={handleFileSelected} />
            <Dialog open={open}>
                <DialogTitle>新建文件夹</DialogTitle>
                <DialogContent>
                    <DialogContentText></DialogContentText>
                    <TextField variant='filled' label='新文件夹名称' onChange={(e) => setNewFolderName(e.target.value)} value={newFolderName}>

                    </TextField>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleNewFolderCreate}>确定</Button>
                    <Button onClick={handleClose}>取消</Button>
                </DialogActions>
            </Dialog>
            <Menu
                sx={{width: '350px'}}
                open={contextMenu !== null}
                onClose={handleContextClose}
                anchorReference="anchorPosition"
                anchorPosition={
                contextMenu !== null
                    ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
                    : undefined
                }
            >   
                <MenuItem onClick={handleContextClose}><ListItemIcon><ContentCopyIcon/></ListItemIcon> <ListItemText>复制</ListItemText></MenuItem>
                <MenuItem onClick={handleContextClose}><ListItemIcon><ContentCopyIcon/></ListItemIcon> <ListItemText>移动</ListItemText></MenuItem>
                <MenuItem onClick={handleContextClose}><ListItemIcon><ContentCopyIcon/></ListItemIcon> <ListItemText>下载</ListItemText></MenuItem>
                <MenuItem onClick={handleContextClose}><ListItemIcon><ContentCopyIcon/></ListItemIcon> <ListItemText>分享</ListItemText></MenuItem>
                <MenuItem onClick={handleContextClose}><ListItemIcon><ContentCopyIcon/></ListItemIcon> <ListItemText>详情</ListItemText></MenuItem>
            </Menu>
            <ProgressPanel>
                <UploadPanel uploadList={uploadList}/>
            </ProgressPanel>
            <Snackbar 
                open={hasMsg}
                message={message}
                autoHideDuration={1500}
                onClose={handleSnackClose}
                anchorOrigin={{vertical:'top', horizontal: 'center'}}
            >    
            </Snackbar>
        </Box>
    
    )
}


export default FilePanel;